import {
  AcModal,
  ACResultModal,
  AuthModal,
  authRouteModal,
  DefaultConfigModal,
  ItemAuthModal,
  RouteModal,
} from '../modal';
import { checkSameAuth } from './check';
const pageAuthProvider = (
  config: DefaultConfigModal,
  route: authRouteModal,
  fatherNode?: RouteModal,
) => {
  const { authProxyAuto = true } = config; //开启自动拼接后拼接appKey

  if (!authProxyAuto || !route.auth) {
    return route.auth;
  }

  let fatherAuthKey: AcModal = fatherNode?.auth;

  if (typeof fatherAuthKey === 'object') {
    fatherAuthKey = <ItemAuthModal>fatherAuthKey.key;
  }

  const authArray = [fatherAuthKey, route.auth];

  return authArray
    .filter(item => {
      return !!item;
    })
    .join(':');
}; //拼接auth
export const itemAuthProvider = (
  config: DefaultConfigModal,
  auth: AcModal,
  fatherNode?: RouteModal,
): AcModal => {
  if (!auth) {
    return auth;
  }

  if (typeof auth === 'string') {
    return pageAuthProvider(config, { auth }, fatherNode);
  }

  const authKey = pageAuthProvider(config, { auth: auth.key }, fatherNode);

  return {
    ...auth,
    key: authKey,
  } as AcModal;
}; //单个权限+上下文
const apiModal = (auth: AcModal, path?: string) => {
  if (!auth || !path) {
    return [];
  }

  if (typeof auth === 'string') {
    return [
      {
        path,
        auth,
      },
    ];
  }

  return [
    {
      path,
      ...auth,
    },
  ];
};
export const ACauth = (
  config: DefaultConfigModal,
  auths?: AuthModal[],
  fatherNode?: RouteModal,
): ACResultModal => {
  if (!auths) {
    return {
      components: [],
      apis: [],
    };
  }
  const components: AcModal[] = [];
  const apis: AuthModal[] = [];
  auths.forEach(item => {
    const { type = 'component', auth, path } = item;
    if (!auth) {
      return;
    }
    const itemAuth = itemAuthProvider(config, auth, fatherNode);
    checkSameAuth(itemAuth, type); //检查是否重复key;
    if (type === 'component') {
      components.push(itemAuth);
      return;
    }
    if (type === 'api') {
      apis.push(...apiModal(itemAuth, path));
      return;
    }
    components.push(itemAuth);
    apis.push(...apiModal(itemAuth, path));
  });
  return {
    components,
    apis,
  };
}; //分离component和api权限
